package com.tanhua.manager.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import com.tanhua.manager.pojo.Manager;
import com.tanhua.manager.service.ManagerService;
import com.tanhua.manager.utils.NoAuthorization;
import com.tanhua.manager.vo.ErrorResult;
import com.tanhua.manager.vo.ManagerVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("system/users")
public class ManagerController {
    @Autowired
    private ManagerService managerService;

    //本类的日志对象
    private static final Logger LOGGER = LoggerFactory.getLogger(ManagerController.class);

    /**
     * 生成验证码图片
     *
     * @param uuid
     * @param response
     * @throws IOException
     */
    @GetMapping("verification")
    @NoAuthorization
    public void verification(@RequestParam("uuid") String uuid, HttpServletResponse response) throws IOException {

        //生成图片验证码,设置长度、宽度、验证码字符数、干扰的元素个数
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(200, 100, 4, 400);

        //获取图片验证码中的验证码
        String code = lineCaptcha.getCode();

        //将验证码和uuid写入到redis
        this.managerService.saveVerificationCode(uuid, code);

        //开启输出流
        ServletOutputStream outputStream = response.getOutputStream();
        //使用输出流响应生成的验证码图片
        lineCaptcha.write(outputStream);
        //关闭输出流
        outputStream.close();
    }

    /*用户登录*/
    @PostMapping("login")
    @NoAuthorization
    public ResponseEntity<Object> login(@RequestBody Map<String, String> param) {//获取请求体中的参数，是用户填写发送的
        try {
            //创建用户对象
            Manager manager = new Manager();
            //赋值封装
            manager.setUsername(param.get("username"));
            manager.setPassword(param.get("password"));
            manager.setVerificationCode(param.get("verificationCode"));
            manager.setUuid(param.get("uuid"));
            //调用业务层登录方法，返回token
            String token = managerService.login(manager);
            Map<Object, Object> map = new HashMap<>();
            map.put("token", token);
            return ResponseEntity.ok(map);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
    }

    /**
     * 查询管理员信息
     *
     * @param
     * @return
     */
    @PostMapping("profile")
    public ManagerVo profile(@RequestHeader("Authorization") String token) {

        ManagerVo managerVo = managerService.queryManagerByToken(token);
        if (null != managerVo) {
            return managerVo;
        }
        return null;
    }


    /**
     * 登出
     *
     * @param token
     * @return
     */
    @PostMapping("logout")
    public ResponseEntity<Object> logout(@RequestHeader("Authorization") String token) {
        ErrorResult.ErrorResultBuilder resultBuilder = ErrorResult.builder().errCode("000000").errMessage("退出失败");
        try {
            boolean bool = this.managerService.logout(token);
            if (bool) {
                //退出成功
                return ResponseEntity.ok(null);
            }
        } catch (Exception e) {
            LOGGER.error("退出异常", e);
        }
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(resultBuilder.build());
    }

}
